<?

class Auth
{
	private $CI;

	public function __construct()
	{
		$this->CI =& get_instance();
	}

	public function check()
	{
		if(!$this->is_user()) {
			flash('Please log in to continue');
			redirect($this->CI->config->item('auth_access_denied_location'));
		}
	}

    public function verify() {
    	$role = $this->CI->session->userdata('role_name');
    	if($role == 'admin' || $role == 'super_admin')
    		redirect('admin/');
    	else
    		redirect('home/');
	}

	public function is_user()
	{
		return $this->CI->session->userdata('user_id') ? true : false;
	}

	public function is_admin()
	{
		return $this->CI->session->userdata('role_name') == 'admin' ? true : false;
	}

	public function is_super_admin()
	{
		return $this->CI->session->userdata('role_name') == 'super_admin' ? true : false;
	}

	public function logout()
	{
		$userdata = array(
			'user_id' => '',
			'user_name' => '',
			'user_password' => '',
			'user_email' => '',
			'fk_role_id' => '',
			'role_name' => ''
		);

		$this->CI->session->unset_userdata($userdata);

		flash('You have successfully logged out.');
		redirect($this->CI->config->item('auth_logout_location'));
	}

	public function login($user_name, $password)
	{
		$this->CI->db->join('roles', 'users.fk_role_id = roles.role_id');
		$user = $this->CI->db->get_where('users', array('user_name' => $user_name))->row_array();

		if($user)
		{
			$msg = 'You have successfully logged in.';
			$password_matches = ($user['user_password'] == sha1($this->CI->config->item('auth_pass_salt1')
									.$password .
									$this->CI->config->item('auth_pass_salt2')));
			$email_is_verified = ($user['user_email_verified'] == true);

			if($password_matches && $email_is_verified) {

				$this->CI->session->set_userdata($user);
				flash($msg);
				$this->verify();

			}elseif(!$password_matches) $msg = 'Wrong password!';
			elseif(!$email_is_verified) $msg = 'Your e-mail address has not yet been verified.';

		}else $msg = 'User not found.';

		flash($msg);
		redirect($this->CI->config->item('auth_login_fail_location'));
	}
}